package com.example.ujsfish.activity;

import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.ujsfish.R;
import com.example.ujsfish.model.Coordinate;
import com.example.ujsfish.model.MyPoint;
import com.example.ujsfish.model.monitor.Data;
import com.example.ujsfish.model.monitor.JsonRootBean;
import com.example.ujsfish.model.ship.PoolName;
import com.example.ujsfish.utils.AppNetService;
import com.example.ujsfish.utils.DeviceName;
import com.example.ujsfish.utils.RetrofitManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static android.content.Context.MODE_PRIVATE;


public class CruiseFragment extends Fragment implements AdapterView.OnItemSelectedListener{
    private RetrofitManager myRetrofitManager = RetrofitManager.getInstance();
    private Retrofit myRetrofit = RetrofitManager.getRetrofit();
    private AppNetService appNetService = myRetrofitManager.getApiService(AppNetService.class);

    private Timer timer;
    private TimerTask task;

    //获取到myView的实时坐标点
    private Coordinate coordinate = Coordinate.getInstance();
    private ArrayList<MyPoint> coordinateList = coordinate.getCoordinateList();

    //Spinner spinner_deviceName;
    private Spinner spinner_poolName;
    private Spinner spinner_pathName;

    private String id;

    private String weight;
    private String device;
    private String pool;
    private String path;

    private View root;
    private TextView text_weight;
    private EditText editPercent;
    private Button btn_startCruise;

    private String type;
    private String percent;
    private String userName;
    private String TAG = "CruiseFragment";
    private SharedPreferences.Editor mEditor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        type = bundle.getString("type");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        SharedPreferences preferences = getActivity().getSharedPreferences("data",MODE_PRIVATE);
        userName = preferences.getString("userName", "");
        mEditor = getActivity().getSharedPreferences("data", MODE_PRIVATE).edit();
        if(root == null){
            root = inflater.inflate(R.layout.cruise_fragment,container,false);
        }

        text_weight = root.findViewById(R.id.text_weight);
        editPercent = root.findViewById(R.id.text_cruisePercent);
        btn_startCruise = root.findViewById(R.id.btn_startCruise);

        id = DeviceName.getDeviceInstance().getDeviceId().get(0);
        device = DeviceName.getDeviceInstance().getDeviceId().get(0);
        getNewPoolData(userName);

        btn_startCruise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                coordinateList.clear();

                Call<JsonRootBean> callM = appNetService.postMonitor(id);
                callM.enqueue(new Callback<JsonRootBean>() {
                    @Override
                    public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {

                        if (response.body().getData().size() != 0) {
                            JsonRootBean jsonRootBean = response.body();
                            Data monitorData = jsonRootBean.getData().get(0);

                            weight = monitorData.getClout();
                            Log.d(TAG, "weight ------------------>" + weight);

                            mEditor.putString("weight", weight);
                            mEditor.putString("device", device);
                            mEditor.putString("pool", pool);
                            mEditor.putString("path", path);
                            mEditor.apply();
                        }

                    }

                    @Override
                    public void onFailure(Call<JsonRootBean> call, Throwable t) {

                    }
                });




                //发送巡航指令
                switch (type) {

                    case "grain":
                        Call<ResponseBody> call = appNetService.postFeeding_Cruise_New(device, pool, path);
                        call.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {

                            }
                        });

                        break;
                    case "fish":
                        Call<ResponseBody> call1 = appNetService.postBaiting_endurance_New(device, pool, path);
                        call1.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {

                            }
                        });
                        break;
                    case "spray":
                        Call<ResponseBody> call2 = appNetService.postSpraying_Cruise_New(device, pool, path);
                        call2.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {

                            }
                        });
                        break;
                    default:
                        break;
                }

            }
        });


        return root;
    }

//    private void initDeviceNameSpinner() {
//        spinner_deviceName = root.findViewById(R.id.spinner_deviceName2);
//
//        for (int i = 0; i < DeviceName.getDeviceInstance().getDeviceId().size() ; i++) {
//            deviceList.add(DeviceName.getDeviceInstance().getDeviceId().get(i));
//        }
//
//        initPoolSpinner(deviceList, spinner_deviceName);
//    }

    private void getNewPathData(String userName) {
        spinner_pathName = root.findViewById(R.id.spinner_pathName4);

        Call<PoolName> responseBodyCall = appNetService.postFindPoolPathNameBU(pool, this.userName);
        responseBodyCall.enqueue(new Callback<PoolName>() {
            @Override
            public void onResponse(Call<PoolName> call, Response<PoolName> response) {
                PoolName poolName = response.body();
                List<String> pathName_list = new ArrayList<>();
                //防止返回的数据中有空数据
                for (String data :
                        poolName.getData()) {
                    if (data != null){
                        pathName_list.add(data);
                    }
                }
                initPoolSpinner(pathName_list, spinner_pathName);
            }

            @Override
            public void onFailure(Call<PoolName> call, Throwable t) {

            }
        });



    }

    private void getNewPoolData(String userName) {
        spinner_poolName = root.findViewById(R.id.spinner_poolName4);

        Call<PoolName> responseBodyCall = appNetService.postFindPoolNameBU(userName);
        responseBodyCall.enqueue(new Callback<PoolName>() {
            @Override
            public void onResponse(Call<PoolName> call, Response<PoolName> response) {
                PoolName poolName = response.body();
                //System.out.println(response.body().toString());
                List<String> poolName_list = new ArrayList<>();
                //防止返回的数据中有空数据
                for (String data :
                        poolName.getData()) {
                    if (data != null){
                        poolName_list.add(data);
                    }
                }
                System.out.println("poolName" + poolName.getData().toString());
                initPoolSpinner(poolName_list, spinner_poolName);

            }

            @Override
            public void onFailure(Call<PoolName> call, Throwable t) {

            }
        });

    }

    private void initPoolSpinner(List<String> poolList, Spinner spinner_poolName) {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this.getActivity(), android.R.layout.simple_list_item_1, poolList);
        //设置样式
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_poolName.setAdapter(arrayAdapter);
        //为Spinner设置选中事件监听器
        spinner_poolName.setOnItemSelectedListener(CruiseFragment.this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String data = parent.getItemAtPosition(position).toString();
        System.out.println("data" + data);
        TextView tv1;
        TextView tv2;

        switch (parent.getId()){
            case R.id.spinner_poolName4:
                pool = data;
                //从服务器获取路径名
                getNewPathData(userName);
                tv2 = (TextView)view;
                //tv2.setTextColor(getResources().getColor(R.color.colorBlack));
                break;
            case R.id.spinner_pathName4:
                path = data;
                break;
            default:break;
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    private void updateUi(AppNetService appNetService) {
        Call<JsonRootBean> call1 = appNetService.postMonitor(id);
        call1.enqueue(new Callback<JsonRootBean>() {
            @Override
            public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
                System.out.println(TAG + response.toString());
                if (response.body().getData().size() != 0) {
                    JsonRootBean jsonRootBean = response.body();
                    Data monitorData = jsonRootBean.getData().get(0);
                    text_weight.setText(monitorData.getClout() + "Kg");

                }
            }

            @Override
            public void onFailure(Call<JsonRootBean> call, Throwable t) {

            }
        });

    }


    @Override
    public void onResume() {
        super.onResume();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                updateUi(appNetService);

            }
        };
        timer.schedule(task,0,2000);
        System.out.println("定时器开启");

    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        System.out.println("定时器关闭");
    }
}